# -*- coding: utf-8 -*-
'''
Created on Sep 8, 2012

@author: bbg
'''
import locale
import time,datetime
from service.public.service_base import ServiceBase
from helper.login_session_manager import LoginSessionManager
from common.debug import Debug
from dbwrapper.company_management.regions import Regions
from dbwrapper.company_management.rights import Rights
from dbwrapper.company_management.company import Company
from dbwrapper.company_management.cdkey import Cdkey
from dbwrapper.company_management import *
import dbwrapper
import json
from sqlalchemy.orm import class_mapper

class CompanyManagementService(ServiceBase):
    '''
    艾云总部管理的相关信息：
    1 全局权限定义表
    2 全局区域表
    3 全局公司信息表
    4 全局CDKEY表

    '''

    def __init__(self, start_response):
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()
        
        
        

    def application(self, params,paths):
        
        #检查 TOKEN 的有效性 
        dbsession =self._returndbsession()
        company_id=params.getfirst("company_id");
        username=params.getfirst("username");
        token=params.getfirst("token");
        intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)

        if intcomp==False:

                return self._responseError(107, 'TOKEN 已经过期')
            
                    
        #开始分流  get or set         
        if paths[2] == 'get':
            return self.getfromcompanymanage(params)
        elif paths[2] == 'set':
            return self.setConfigApplication(params)
             
             
        
        return self._responseError(-1, "操作失败")

        
        
        
    def getfromcompanymanage(self, params):
        '''
                  客户需要获取基本信息 比如：权限，区域        
        '''
        #TODO:       
        if params.has_key('type') == False:
            self.debug.e('CompanyManagementService:no \'type\' parameters')
            return self._responseInvalidParam()
        
                
        config_table = params.getfirst('type')
        
        self.debug.d("tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["regions"] = regions.Regions
        config_table_classes["rights"] = rights.Rights 
        config_table_classes["company"] = company.Company  
        config_table_classes["cdkey"] = cdkey.Cdkey     
        
        
        config_orderby = {}
        config_orderby["regions"] ="`range` asc "
        config_orderby["rights"] = "id"
        config_orderby["company"] = "region_id asc,id asc "
        config_orderby["cdkey"] = "shop_id asc,id asc "

        
                          
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby=config_orderby[config_table]
            return self.getfromcompanymanageAction(params, table_class,orderby)
        else:
            return self._responseError(-1, "unkonw configure")
        


    def getfromcompanymanageAction(self, params, table_class,orderby):
        '''
                       对读配置的表的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            #过滤出要更新的表字段名和字段值
            dbsession = self._returndbsession()  
            company_id = params.getfirst('company_id')                     
            #获取记录操作
            if (table_class==company.Company):
                query_result = dbsession.query(table_class).filter(Company.id == company_id).order_by(orderby).all()
            elif (table_class==cdkey.Cdkey):
                query_result = dbsession.query(table_class).filter(Cdkey.company_id == company_id).order_by(orderby).all()
            else:
                query_result = dbsession.query(table_class).filter().order_by(orderby).all()
            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                                                           

            returnlist=[]                           
            dicmy={}
            dicmy["ret"]=0
            dicmy["msg"]='success'
            icount=0
            for r in query_result:
                icount=1
                dicmyFF={} 
                for field in  table_fields:
                    temp=getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmyFF[field]=str(temp)                        
                    else:
                        dicmyFF[field]=temp
                    
                strtemp=json.dumps(dicmyFF)                
                returnlist.append(strtemp)
                            
            if icount == 0:          
               
                return self._responseError(6, "记录为空")
                                         
            dicmy['data']=returnlist
            
            return self._response(json.dumps(dicmy))         
        except Exception, e:
       
            self.debug.e('CompanyManagementService.getfromcompanymanageAction: exception:%s' % e)
            return self._responseInvalidParam()
        
            
    
        
        

    def setConfigApplication(self, params):
        '''
                     修改  添加  删除  相关的信息 
        '''
       
        if params.has_key('config_table') == False:
            self.debug.e('CompanyManagementService.setConfigApplication:no \'config_table\' parameters')
            return self._responseInvalidParam()
                        
        config_table = params.getfirst('config_table')
        
        config_table_classes = {}
        config_table_classes["regions"] = regions.Regions
        config_table_classes["rights"] = rights.Rights 
        config_table_classes["company"] = company.Company  
        config_table_classes["cdkey"] = cdkey.Cdkey                       
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self.setConfigAction(params, table_class)
        else:
            return self.response(-1, "unkonw configure")
        
 
        
        
        
    def setConfigAction(self, params, table_class):
        '''
                    对写配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            cmd = params.getfirst('cmd')
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in params.keys():
                if param not in exclude_fields:
                    table_fields[param] = params.getfirst(param)
                                 
            
            dbsession =self._returndbsession()     
            if cmd == 'add':
                
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    dbsession.add(table_object)
                    dbsession.commit()
                except Exception, e:
                    self.debug.e("CompanyManagementService.setConfigAction() add table %s failed" % table_object)
                     
                    return self._responseError(-1, "add failed");
                
                 
                output = {"ret":0,"msg":"add ok"}
                return self._response(json.dumps(output))
            elif cmd == 'update':

                
                #更新记录操作
                #获取要修改的表where字段
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() ==0:
                   
                    self.debug.e("CompanyManagementService.setConfigAction(): no such record")
                    return self._responseError(-1, "no such record")
                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                dbsession.commit()
                
                output = {'ret':0, 'msg' : 'update ok'}
                return self._response(json.dumps(output))
            elif cmd == 'del':                
                #删除记录操作 目前没有用到
                
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                dbsession.query(table_class).filter(columnAttr == where_value).delete()
                dbsession.commit()
                
                
                output ={'ret':0, 'msg' : 'delete ok'}
                return self._response(json.dumps(output))
        except Exception, e:
             
            self.debug.e('ShopConfigService.setConfigAction(): exception:%s' % e)
            return self._responseInvalidParam()
                